#-*- coding:utf-8 -*-
"""
简谱编译器
"""

import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *


# 自定义高亮显示
class High(QSyntaxHighlighter):

    def __init__(self, parent=None):
        super(High, self).__init__(parent)  # 必须继承一个父物体，该功能只是其修饰作用，相当于要传一个引用进来

        # 创建自定义字符显示格式
        baseFormat = QTextCharFormat()
        baseFormat.setFontFamily('courier')
        baseFormat.setFontPointSize(12)

        self.normal_format = QTextCharFormat(baseFormat)
        self.normal_format.setForeground(QColor('#000000'))

        self.keyword_format = QTextCharFormat(baseFormat)  # 复制构造
        self.keyword_format.setForeground(QColor('#f76002'))
        self.keyword_format.setFontWeight(QFont.Bold)
        # keyword_format.setFontItalic(True)  # 设置斜体

        KEYWORDS = ['#', '\(', '\)', '\{', '\}', '\/', '\?', '\<', '\>', '\`', 'b', 'n', 'f', 'ff', 'fff',
                    'mf']  # 注意正则特殊符号都是用\来修饰

        # 正则 relu
        # self.keyrelu = QRegExp('|'.join([r"\b%s\b" % keyword for keyword in KEYWORDS]))
        self.keyrelu = QRegExp('|'.join(KEYWORDS))

    def highlightBlock(self, p_str):
        print(p_str)
        textLength = len(p_str)
        prevState = self.previousBlockState()
        self.setFormat(0, textLength, self.normal_format)
        i = self.keyrelu.indexIn(p_str)
        while i >= 0:
            print(i)
            length = self.keyrelu.matchedLength()
            self.setFormat(i, length, self.keyword_format)
            i = self.keyrelu.indexIn(p_str, i + length)

        if not p_str:
            pass

    def rehighlight(self):
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        QSyntaxHighlighter.rehighlight(self)
        QApplication.restoreOverrideCursor()


# 自定义QTextEdit,主要是取消掉tab键的默认空格长度
class MyText(QTextEdit):

    def __init__(self):
        super(MyText, self).__init__()

        # def event(self, QEvent):
        #     if QEvent.type() == QEvent.K
        self.setTabStopWidth(1)
        # self.setTabStopDistance(0)

    def keyPressEvent(self, QKeyEvent):
        if QKeyEvent.key() == Qt.Key_Tab:
            cursor = self.textCursor()
            cursor.insertText("|")

        super(MyText, self).keyPressEvent(QKeyEvent)


class Test(QWidget):

    def __init__(self):
        super(Test, self).__init__()

        self.main_layout = QHBoxLayout()
        self.my = MyText()
        self.high = High(self.my.document())  # 关键点： 自定义的高亮只起到修饰的作用，本身不是widget
        self.main_layout.addWidget(self.my)
        self.setLayout(self.main_layout)
        # print('A:',)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    t = Test()
    t.show()
    sys.exit(app.exec_())

